function showAddElderlyForm() {
    document.body.insertAdjacentHTML('beforeend', '<div class="modal-overlay"></div>');
    const form = `
        <div class="modal">
            <h3>添加档案</h3>
            <form id="elderly-form">
                <div>
                    <label>姓名：</label>
                    <input type="text" name="name" required>
                </div>
                <div>
                    <label>性别：</label>
                    <select name="gender">
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
                <div>
                    <label>出生日期：</label>
                    <input type="date" name="birth_date" required>
                </div>
                <div>
                    <label>联系电话：</label>
                    <input type="tel" name="phone" required>
                </div>
                <div>
                    <label>地址：</label>
                    <input type="text" name="address">
                </div>
                <div>
                    <label>紧急联系人：</label>
                    <input type="text" name="emergency_contact">
                </div>
                <div>
                    <label>紧急联系电话：</label>
                    <input type="tel" name="emergency_phone">
                </div>
                <button type="submit">提交</button>
                <button type="button" onclick="closeModal()">取消</button>
            </form>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', form);
    
    document.getElementById('elderly-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData.entries());
        
        try {
            const response = await fetch('/api/elderly', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });
            
            if (response.ok) {
                closeModal();
                loadElderlyList();
            }
        } catch (error) {
            console.error('Error:', error);
        }
    });
}

function closeModal() {
    document.querySelector('.modal').remove();
    document.querySelector('.modal-overlay').remove();
}

// 显示指定部分
function showSection(sectionId) {
    document.querySelectorAll('.section').forEach(section => {
        section.classList.add('hidden');
    });
    document.getElementById(sectionId).classList.remove('hidden');
    
    if (sectionId === 'elderly-list') {
        loadElderlyList();
    }
}

// 加载老年人列表
async function loadElderlyList() {
    try {
        const response = await fetch('/api/elderly');
        const data = await response.json();
        const table = document.getElementById('elderly-table');
        
        let html = `
            <table>
                <thead>
                    <tr>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>出生日期</th>
                        <th>联系电话</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        data.forEach(elderly => {
            html += `
                <tr>
                    <td>${elderly.name}</td>
                    <td>${elderly.gender}</td>
                    <td>${elderly.birth_date}</td>
                    <td>${elderly.phone}</td>
                    <td>
                        <button onclick="viewHealthRecords(${elderly.id})">查看记录</button>
                        <button onclick="viewHealthAdvice(${elderly.id})">查看建议</button>
                        <button onclick="showEditElderlyForm(${elderly.id})" class="edit-btn">修改档案</button>
                        <button onclick="deleteElderly(${elderly.id}, '${elderly.name}')" class="delete-btn">删除档案</button>
                    </td>
                </tr>
            `;
        });
        
        html += '</tbody></table>';
        table.innerHTML = html;
    } catch (error) {
        console.error('Error:', error);
    }
}

// 查看健康记录
async function viewHealthRecords(elderlyId) {
    try {
        const response = await fetch(`/api/health_record?elderly_id=${elderlyId}`);
        const data = await response.json();
        
        document.getElementById('health-record').classList.remove('hidden');
        document.getElementById('elderly-list').classList.add('hidden');
        
        const recordSection = document.getElementById('health-record');
        recordSection.querySelector('h2').innerHTML = `健康记录 - ${data[0]?.elderly_name || ''}`;
        
        const addButton = recordSection.querySelector('.action-bar button');
        addButton.onclick = () => showAddRecordForm(elderlyId);
        
        const tbody = document.getElementById('record-list');
        let html = '';
        data.forEach(record => {
            const indicators = record.indicators || {};
            const statusClass = getHealthStatusClass(record.health_status);
            html += `
                <tr>
                    <td>${record.record_date}</td>
                    <td>${indicators.temperature || '-'}</td>
                    <td>${indicators.blood_pressure ? 
                         indicators.blood_pressure.systolic + '/' + 
                         indicators.blood_pressure.diastolic : '-'}</td>
                    <td class="health-status ${statusClass}">${record.health_status || '-'}</td>
                    <td>${record.description || '-'}</td>
                    <td>${record.doctor_advice || '-'}</td>
                </tr>
            `;
        });
        
        tbody.innerHTML = html;
    } catch (error) {
        console.error('Error:', error);
    }
}

// 查看健康建议
async function viewHealthAdvice(elderlyId) {
    try {
        const response = await fetch(`/api/health_advice?elderly_id=${elderlyId}`);
        const data = await response.json();
        
        document.getElementById('health-advice').classList.remove('hidden');
        document.getElementById('elderly-list').classList.add('hidden');
        
        if (data.length === 0) {
            document.getElementById('advice-content').innerHTML = 
                '<div class="no-data">暂无健康记录，无法生成建议</div>';
            return;
        }
        
        const statusClass = getHealthStatusClass(data[0].health_status);
        document.getElementById('current-health-status').className = `health-status ${statusClass}`;
        document.getElementById('current-health-status').textContent = data[0].health_status;
        
        const adviceContent = document.getElementById('advice-content');
        let html = `
            <div class="advice-list">
                <div class="advice-header">
                    <h3>根据您最近的健康状况，为您提供以下建议：</h3>
                    <p class="advice-date">更新时间：${data[0].created_at}</p>
                </div>
        `;
        
        data.forEach(advice => {
            html += `
                <div class="advice-item">
                    <h4>${advice.advice_type}</h4>
                    <p>${advice.content}</p>
                </div>
            `;
        });
        
        html += '</div>';
        adviceContent.innerHTML = html;
    } catch (error) {
        console.error('Error:', error);
    }
}

// 显示添加健康记录表单
function showAddRecordForm(elderlyId) {
    const form = `
        <div class="modal">
            <h3>添加健康记录</h3>
            <form id="record-form">
                <input type="hidden" name="elderly_id" value="${elderlyId}">
                <div>
                    <label>体温(℃)：</label>
                    <input type="number" name="temperature" step="0.1" required>
                </div>
                <div>
                    <label>收缩压(mmHg)：</label>
                    <input type="number" name="systolic_pressure" required>
                </div>
                <div>
                    <label>舒张压(mmHg)：</label>
                    <input type="number" name="diastolic_pressure" required>
                </div>
                <div>
                    <label>记录时间：</label>
                    <input type="datetime-local" name="record_date" required>
                </div>
                <div>
                    <label>描述：</label>
                    <textarea name="description" rows="3"></textarea>
                </div>
                <div>
                    <label>医生建议：</label>
                    <textarea name="doctor_advice" rows="3"></textarea>
                </div>
                <div class="form-buttons">
                    <button type="submit">提交</button>
                    <button type="button" onclick="closeModal()">取消</button>
                </div>
            </form>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', form);
    
    // 设置当前时间为默认值
    const now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    document.querySelector('input[name="record_date"]').value = now.toISOString().slice(0, 16);
    
    document.getElementById('record-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData.entries());
        
        const recordData = {
            elderly_id: parseInt(data.elderly_id),
            record_type: '日常监测',
            record_date: data.record_date,
            description: data.description || '',
            doctor_advice: data.doctor_advice || '',
            indicators: {
                temperature: parseFloat(data.temperature),
                blood_pressure: {
                    systolic: parseInt(data.systolic_pressure),
                    diastolic: parseInt(data.diastolic_pressure)
                }
            }
        };
        
        try {
            const response = await fetch('/api/health_record', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(recordData)
            });
            
            if (response.ok) {
                alert('记录添加成功！');
                closeModal();
                viewHealthRecords(recordData.elderly_id);
            } else {
                alert('记录添加失败，请重试！');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('提交出错，请重试！');
        }
    });
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    loadElderlyList();
});

// 添加返回按钮功能
function backToElderlyList() {
    showSection('elderly-list');
}

// 添加健康状态样式函数
function getHealthStatusClass(status) {
    switch(status) {
        case '非常健康': return 'status-excellent';
        case '良好': return 'status-good';
        case '及格': return 'status-fair';
        case '需要治疗': return 'status-poor';
        default: return '';
    }
}

// 删除老年人档案
async function deleteElderly(elderlyId, elderlyName) {
    if (!confirm(`确定要删除 ${elderlyName} 的档案吗？\n注意：这将同时删除该用户的所有健康记录和健康建议！`)) {
        return;
    }
    
    try {
        const response = await fetch(`/api/elderly/${elderlyId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('档案删除成功！');
            loadElderlyList();  // 重新加载列表
        } else {
            alert('删除失败：' + data.message);
        }
    } catch (error) {
        console.error('Error:', error);
        alert('删除出错，请重试！');
    }
}

// 显示修改老年人档案表单
async function showEditElderlyForm(elderlyId) {
    try {
        // 获取老年人详细信息
        const response = await fetch(`/api/elderly/${elderlyId}`);
        const elderly = await response.json();
        
        const form = `
            <div class="modal">
                <h3>修改档案</h3>
                <form id="elderly-edit-form">
                    <input type="hidden" name="id" value="${elderly.id}">
                    <div>
                        <label>姓名：</label>
                        <input type="text" name="name" value="${elderly.name}" required>
                    </div>
                    <div>
                        <label>性别：</label>
                        <select name="gender">
                            <option value="男" ${elderly.gender === '男' ? 'selected' : ''}>男</option>
                            <option value="女" ${elderly.gender === '女' ? 'selected' : ''}>女</option>
                        </select>
                    </div>
                    <div>
                        <label>出生日期：</label>
                        <input type="date" name="birth_date" value="${elderly.birth_date}" required>
                    </div>
                    <div>
                        <label>联系电话：</label>
                        <input type="tel" name="phone" value="${elderly.phone}" required>
                    </div>
                    <div>
                        <label>地址：</label>
                        <input type="text" name="address" value="${elderly.address || ''}">
                    </div>
                    <div>
                        <label>紧急联系人：</label>
                        <input type="text" name="emergency_contact" value="${elderly.emergency_contact || ''}">
                    </div>
                    <div>
                        <label>紧急联系电话：</label>
                        <input type="tel" name="emergency_phone" value="${elderly.emergency_phone || ''}">
                    </div>
                    <div class="form-buttons">
                        <button type="submit">保存</button>
                        <button type="button" onclick="closeModal()">取消</button>
                    </div>
                </form>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', form);
        
        document.getElementById('elderly-edit-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData.entries());
            
            try {
                const response = await fetch(`/api/elderly/${data.id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('档案修改成功！');
                    closeModal();
                    loadElderlyList();
                } else {
                    alert('修改失败：' + result.message);
                }
            } catch (error) {
                console.error('Error:', error);
                alert('修改出错，请重试！');
            }
        });
    } catch (error) {
        console.error('Error:', error);
        alert('加载档案信息失败，请重试！');
    }
} 